//
//  PublishReportTableViewController.m
//  suRead
//
//  Created by 李 诗洋 on 15/11/12.
//  Copyright © 2015年 bao. All rights reserved.
//

#import "PublishReportTableViewController.h"
#import "ServiceNews.h"
#import "AccountManager.h"

#import "Masonry.h"
#import "UIControl+Blocks.h"
#import "CDImagePicker.h"
#import "ZYQAssetPickerController.h"
#import "UIViewController+HUD.h"
#import "UIImageView+WebCache.h"

#import "AboutReportViewController.h"
#import "ClaimsOfRightsAndInterestsViewController.h"
#import "ServiceUserNew.h"

static CGFloat photoImageViewWidthAndHegiht = 64.0f;
static CGFloat photoImageViewSpacing = 10.0f;

@interface PublishReportTableViewController ()<UIActionSheetDelegate,ZYQAssetPickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate>
@property (strong, nonatomic) IBOutlet UITextField *rebellionTitleTextField;
@property (strong, nonatomic) IBOutlet UITextView *materialContentTextView;
@property (strong, nonatomic) IBOutlet UITextField *contactTextField;

@property (strong, nonatomic) IBOutlet UIScrollView *reportPhotoContainer;
@property (strong, nonatomic) IBOutlet UIButton *rebellionSetButton;
@property (strong, nonatomic) UIView *reportPhotoContainerView;
@property (strong, nonatomic) UILabel *placeholderLabel;

@property (strong,nonatomic) UIButton *addPhotoButton;

@property (strong, nonatomic)CDImagePicker *imagePicker;

@property (strong,nonatomic)NSMutableArray *reportAddImageArray;


@property (nonatomic,assign) BOOL isOpen;
@property (weak, nonatomic) IBOutlet UISwitch *openSwitch;
@property (weak, nonatomic) IBOutlet UILabel *openLable;

@end

@implementation PublishReportTableViewController

/**
 *  权益
 *
 *  @param sender
 */
- (IBAction)rightsAndInterests:(id)sender
{
    UIStoryboard *personalCenterStoryBoard = [UIStoryboard storyboardWithName:@"PersonalCenter" bundle:[NSBundle mainBundle]];
    ClaimsOfRightsAndInterestsViewController *controller = [personalCenterStoryBoard instantiateViewControllerWithIdentifier:@"ClaimsOfRightsAndInterestsViewController"];
    [self.navigationController pushViewController:controller animated:YES];
}

/**
 *  爆料须知
 *
 *  @param sender
 */
- (IBAction)about:(id)sender
{
    UIStoryboard *personalCenterStoryBoard = [UIStoryboard storyboardWithName:@"PersonalCenter" bundle:[NSBundle mainBundle]];
    AboutReportViewController *controller = [personalCenterStoryBoard instantiateViewControllerWithIdentifier:@"AboutReportViewController"];
    [self.navigationController pushViewController:controller animated:YES];
}

-(void)switchAction:(id)sender
{
    UISwitch *switchButton = (UISwitch*)sender;
    BOOL isButtonOn = [switchButton isOn];
    if (isButtonOn) {
        self.openLable.text = @"公开";
        self.isOpen = YES;
    }else {
        self.openLable.text = @"不公开";
        self.isOpen = NO;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isOpen = YES;
    
    [self.openSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];

    
    self.tableView.sectionFooterHeight = 0;
    
    self.reportAddImageArray = [NSMutableArray new];
    
    __weak typeof (self)weak_self = self;
    
    //发约照片初始化
    self.reportPhotoContainer.backgroundColor = [UIColor clearColor];
    //self.datingPhotoContainer.delegate = self;
    self.reportPhotoContainer.showsHorizontalScrollIndicator = NO;
    self.reportPhotoContainer.showsVerticalScrollIndicator = NO;
    self.reportPhotoContainer.bounces = YES;
    
    self.reportPhotoContainerView = [UIView new];
    
    self.addPhotoButton = [UIButton new];
    [self.addPhotoButton setImage:[UIImage imageNamed:@"photoadd"] forState:UIControlStateNormal];
    [self.addPhotoButton addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        [weak_self.view endEditing:YES];
        UIActionSheet *chooseImageSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:weak_self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"照相",@"相册", nil];
        [chooseImageSheet showInView:weak_self.view];
    }];
    [self.reportPhotoContainerView addSubview:self.addPhotoButton];
    [self.addPhotoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(photoImageViewWidthAndHegiht);
        make.width.mas_equalTo(photoImageViewWidthAndHegiht);
        make.centerY.equalTo(weak_self.addPhotoButton.superview.mas_centerY);
        make.left.equalTo(weak_self.addPhotoButton.superview.mas_left);
    }];
    
    [self.reportPhotoContainer addSubview:self.reportPhotoContainerView];
    [self.reportPhotoContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weak_self.reportPhotoContainerView.superview).insets(UIEdgeInsetsZero);
        make.height.mas_equalTo(weak_self.reportPhotoContainerView.superview.mas_height);
        make.width.mas_equalTo(weak_self.reportPhotoContainerView.superview.mas_width);
    }];
    
//    self.materialContentTextView.layer.cornerRadius = 5;
//    self.materialContentTextView.layer.masksToBounds = YES;
//    self.materialContentTextView.layer.borderColor = [UIColor colorWithRed:233/255.0f green:233/255.0f blue:233/255.0f alpha:1.0f].CGColor;
//    self.materialContentTextView.layer.borderWidth = 1.0f;
    
    self.materialContentTextView.delegate = self;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(5, 7, 200, 20)];
    label.enabled = NO;
    label.text = @"请输入报料内容";
    label.font =  [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:15.0f];
    label.textColor = [UIColor lightGrayColor];
    self.placeholderLabel = label;
    [self.materialContentTextView addSubview:self.placeholderLabel];
}

- (void)textViewDidChange:(UITextView *)textView{
    if ([textView.text length] == 0) {
        [self.placeholderLabel setHidden:NO];
    }else{
        [self.placeholderLabel setHidden:YES];
    }
}

#pragma mark - 上传照片

#pragma mark 更改UI 减图片重新排列
- (void)updateUIbyDelete
{
    for (NSInteger i = self.reportPhotoContainerView.subviews.count - 1; i >=0 ; i --) {
        UIView *view = (UIView *)[self.reportPhotoContainerView.subviews objectAtIndex:i];
        [view mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(photoImageViewWidthAndHegiht);
            make.width.mas_equalTo(photoImageViewWidthAndHegiht);
            make.centerY.equalTo(view.superview);
            make.left.equalTo(view.superview).with.offset(photoImageViewWidthAndHegiht * ((self.reportPhotoContainerView.subviews.count - 1) - i) + photoImageViewSpacing * ((self.reportPhotoContainerView.subviews.count - 1) - i));
        }];
    }
}

#pragma mark 更改UI 加图片
- (void)updateUIbyUploadSucceed:(NSString *)photoUrl
{
    [self.reportAddImageArray addObject:photoUrl];
    
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [self.reportPhotoContainerView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(photoImageViewWidthAndHegiht);
        make.width.mas_equalTo(photoImageViewWidthAndHegiht);
        make.centerY.equalTo(view.superview);
        make.left.equalTo(view.superview).with.offset(photoImageViewWidthAndHegiht * (self.reportAddImageArray.count - 1) + photoImageViewSpacing * (self.reportAddImageArray.count - 1));
    }];
    
    UIImageView *imageView = [UIImageView new];
    [imageView sd_setImageWithURL:[NSURL URLWithString:photoUrl]];
    [view addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(imageView.superview).insets(UIEdgeInsetsZero);
    }];
    
    UIButton *deleteButton = [UIButton new];
    [deleteButton setImage:[UIImage imageNamed:@"deletbutton"] forState:UIControlStateNormal];
    [deleteButton addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        [view removeFromSuperview];
        [self.reportAddImageArray removeObject:photoUrl];
        [self updateUIbyDelete];
    }];
    [view addSubview:deleteButton];
    [deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(24.0f);
        make.width.mas_equalTo(24.0f);
        make.left.equalTo(deleteButton.superview);
        make.top.equalTo(deleteButton.superview);
    }];

    [self.addPhotoButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(photoImageViewWidthAndHegiht);
        make.width.mas_equalTo(photoImageViewWidthAndHegiht);
        make.centerY.equalTo(self.addPhotoButton.superview);
        make.left.equalTo(self.addPhotoButton.superview).with.offset(photoImageViewSpacing * self.reportAddImageArray.count + photoImageViewWidthAndHegiht * self.reportAddImageArray.count);
    }];
    
    //改变存放的scrollview的内容大小
    [self.reportPhotoContainerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.reportPhotoContainerView.superview).insets(UIEdgeInsetsZero);
        make.height.mas_equalTo(self.reportPhotoContainerView.superview.mas_height);
        make.width.mas_equalTo(photoImageViewWidthAndHegiht * (self.reportAddImageArray.count + 1) + photoImageViewSpacing * (self.reportAddImageArray.count + 1 + 1));
    }];
}


#pragma mark UIActionSheetDelegate Method
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 0://Take picture
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                [self uploadByCamera:UIImagePickerControllerSourceTypeCamera];
            }
            else
            {
                NSLog(@"模拟器无法打开相机");
            }
            break;
        case 1:
        {
            [self uploadByPhotoLibrary];
        }
            break;
        default:
            break;
    }
}

#pragma mark 拍照上传
- (void)uploadByCamera:(UIImagePickerControllerSourceType)type
{
    __weak typeof(self) safe_self = self;
    self.imagePicker = [CDImagePicker imagePickerWith:self
                                                 type:type
                                        completeBlock:^(NSString *imagePath_) {
                                            [safe_self uploadNetWork:@[imagePath_]];
                                        }];
    [self.imagePicker choose];
}

#pragma mark 相册选择上传
- (void)uploadByPhotoLibrary
{
    ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
    picker.maximumNumberOfSelection = 1;
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups = NO;
    picker.delegate = self;
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
            NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
            return duration >= 5;
        } else {
            return YES;
        }
    }];
    
    [self presentViewController:picker animated:YES completion:NULL];
}

#pragma mark ZYQAssetPickerController Delegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    __weak typeof(self) safe_self = self;
    
    NSMutableArray *photoArrary = [NSMutableArray new];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        for (int i = 0; i < assets.count; i ++)
        {
            NSString *imageName = [[[NSUUID alloc] init] UUIDString];
            
            ALAsset *asset        = assets[i];
            UIImage *tempImg      = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
            [safe_self writeCache:tempImg chacheName:imageName];
            [photoArrary addObject:[[safe_self cacheDirectory] stringByAppendingPathComponent:imageName]];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //[safe_self showHUDProgress:@"上传中"];
            [safe_self uploadNetWork:photoArrary];
        });
        
    });
}

#pragma mark 获取图片缓存目录
- (NSString *)cacheDirectory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
    return [paths objectAtIndex:0];
}

#pragma mark 写入文件
- (void)writeCache:(UIImage *)image_ chacheName:(NSString *)cacheName
{
    NSString *cachePath = [[self cacheDirectory] stringByAppendingPathComponent:cacheName];
    //图像压缩
    NSData *imageData = UIImageJPEGRepresentation(image_,.5f);
    [imageData writeToFile:cachePath atomically:YES];
}

#pragma mark 网络上传
- (void)uploadNetWork:(NSArray *)array
{
    __weak typeof(self) safe_self = self;
    for (int i = 0; i < array.count; i ++)
    {
        [ServiceNews doUpdatePhotoList:array[i]
                               success:^(id responseObject, NSString *message)
        {
            [safe_self updateUIbyUploadSucceed:responseObject];
        }
                               failure:^(NSString *message)
        {
            
            
        }];
    }
}
- (void)rebellionSetButtonClick
{
    if([self.rebellionTitleTextField.text isEqualToString:@""]){
        return [theAppDelegate alert:@"报料标题不能为空!"];
    }
    if([self.materialContentTextView.text isEqualToString:@""]){
        return [theAppDelegate alert:@"报料内容不能为空!"];
    }
    
    //图片
    NSString *picList = @"";
    for (int i = 0; i < self.reportAddImageArray.count; i++)
    {
        picList = [picList stringByAppendingString:[self.reportAddImageArray objectAtIndex:i]];
        if (i != self.reportAddImageArray.count - 1) {
            picList = [picList stringByAppendingString:@";"];
        }
    }
    
    [ServiceNews doReport:self.rebellionTitleTextField.text
                  content:self.materialContentTextView.text
                     imgs:picList
                  contact:self.contactTextField.text
                 username:[AccountManager sharedAccountManager].f_userName
                 ispublic:self.isOpen
                  success:^(id responseObject, NSString *message)
    {
        [ServiceUserNew doAddScore:AddScoreType_baoliao
                           success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {}
                           failure:^(NSString * _Nonnull message) {}];
        
        [self showHUDText:@"发布成功!"];
        [self.navigationController popViewControllerAnimated:YES];
    }
                  failure:^(NSString *message)
    {
        
        
    }];
}


#pragma mark - 滚动收键盘
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

@end
